import menus from './router/menu'
import { router } from './router'
import { useMenu } from './store/menu'
export default function permissRoute (userInfo = {}) {
  const menu = useMenu()
  const { role, permissions } = userInfo
  // 布局路由
  const layout = {
    path: '/',
    name: 'layout',
    component: () => import('@/layout/main.vue'),
    redirect: '',
    children: []
  }
  if (role === '超级管理员') {
    layout.children = menus
  } else {
    layout.children = routeFilter(menus, permissions)
  }
  menu.setMenu(layout.children) // 保存权限菜单，生成左侧菜单
  router.addRoute(layout)
  router.replace(router.currentRoute.value.fullPath) // 路由添加后，需要重定向路由
}
// 递归查找拥有权限的路由
function routeFilter (routes, permiss = []) {
  const userRoutes = []
  routes.forEach((item) => {
    if (item.children?.length) {
      const children = routeFilter(item.children, permiss)
      if (children.length) {
        userRoutes.push({ ...item, children })
      }
    } else {
      if (permiss.includes(item.permission)) {
        userRoutes.push({ ...item })
      }
    }
  })
  return userRoutes
}
